package com.vivo.ic.dm;

import java.io.File;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

import com.vivo.ic.VLog;

class SpaceHelper {
    private static final String TAG = Constants.PRE_TAG + "SpaceHelper";
    // 10M
    private static final long sDownloadDataDirLowSpaceThreshold = 10 * 1024 * 1024;
    
    public static void checkSpace(Context context, String path, long targetBytes) throws StopRequestException {
        VLog.d(TAG, "checkSpace path: " + path + " targetBytes: " + targetBytes);
        if (targetBytes <= 0) {
            VLog.w(TAG, "abort check space because of  targetBytes: " + targetBytes);
            return;
        }
        
        if (path == null) {
            throw new IllegalArgumentException("path can't be null");
        }
        
        File root = null;
        if (path.startsWith(context.getCacheDir().getPath())) {
            root = context.getCacheDir();
        } else if (path.startsWith(Environment.getExternalStorageDirectory().getPath())) {
            root = Environment.getExternalStorageDirectory();
        } else if (path.startsWith(Environment.getDownloadCacheDirectory().getPath())) {
            root = Environment.getDownloadCacheDirectory();
        } else {
            throw new IllegalArgumentException("root of path unhandled !!!");
        }
        //TODO TEST
        long bytesAvailable = getAvailableBytesInFileSystemAtGivenRoot(root);
        VLog.d(TAG,"bytesAvailable " + bytesAvailable);
        if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
            throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
                    "space too low !! " + root + " space left " + bytesAvailable + "b, stop downloading!");
        }
        
        if (bytesAvailable < targetBytes) {
            throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
                    "space not enough !! " + root + " space left " + bytesAvailable + "b, targetBytes is " + targetBytes);
        }
    }
    
    static long getAvailableBytesInFileSystemAtGivenRoot(File root) {
        StatFs stat = new StatFs(root.getPath());
        // put a bit of margin (in case creating the file grows the system by a
        // few blocks)
        long availableBlocks = (long) stat.getAvailableBlocks() - 4;
        long size = stat.getBlockSize() * availableBlocks;
        VLog.i(TAG, "available space (in bytes) in filesystem rooted at: " + root.getPath() + " is: " + size);
        return size;
    }
}
